package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.ReportTimed;
import com.ruoyi.system.domain.ValidationGroups.*;
import com.ruoyi.system.service.IProjectAuthorizeService;
import com.ruoyi.system.service.IReportTimedService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/system/report_timed")
public class ReportTimedController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IReportTimedService reportTimedService;
    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;

    @PreAuthorize("@ss.hasPermi('system:report_timed:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportTimed reportTimed){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        reportTimed.setCompanyId(companyId);
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            //当前为客户公司下面用户
            Long customerId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            List<SysUser> sysUsers = sysUserService.queryUserInfo(customerId);
            Set<String> usernames = new HashSet<>();
            if (CollUtil.isNotEmpty(sysUsers)){
                usernames = sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toSet());
            }
            reportTimed.setUsernames(usernames);
        }
        startPage();
        List<ReportTimed> reportTimeds = reportTimedService.queryList(reportTimed);
        return getDataTable(reportTimeds);
    }
    @PreAuthorize("@ss.hasPermi('system:report_timed:get_info')")
    @GetMapping("/get_info")
    public AjaxResult getInfo(Integer id){
        ReportTimed param = new ReportTimed();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        param.setCompanyId(companyId);
        param.setId(id);
        ReportTimed reportTimed = reportTimedService.getOne(param);
        if (reportTimed == null){
            reportTimed = new ReportTimed();
        }
        return AjaxResult.success(reportTimed);
    }

    @PreAuthorize("@ss.hasPermi('system:report_timed:add')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated(Create.class) ReportTimed reportTimed){
        reportTimedService.checkIsExit(reportTimed);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        reportTimed.setCompanyId(companyId);
        reportTimed.setCreateBy(loginUser.getUsername());
        reportTimed.setCreateTime(new Date());
        reportTimed.setData(JSONUtil.toJsonStr(reportTimed.getChoseData()));
        if (reportTimedService.add(reportTimed)){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PreAuthorize("@ss.hasPermi('system:report_timed:edit')")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated(Update.class) ReportTimed reportTimed){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //验证操作权限
        projectAuthorizeService.checkReportOperationStatus(user,reportTimed.getId());
        reportTimedService.checkIsExit(reportTimed);
        reportTimed.setData(JSONUtil.toJsonStr(reportTimed.getChoseData()));
        if (reportTimedService.update(reportTimed)){
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.success("修改失败");
    }

    @PreAuthorize("@ss.hasPermi('system:report_timed:delete')")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable @NotNull(message = "id不能为null") Integer id){
        //验证操作权限
        SysUser user = SecurityUtils.getLoginUser().getUser();
        projectAuthorizeService.checkReportOperationStatus(user,id);
        ReportTimed param = new ReportTimed();
        param.setId(id);
        if (reportTimedService.delete(param)){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }
}
